﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using ImageTools.IO;
using ImageTools.IO.Gif;
using MailRuWrapper;
using MailRuWrapper.Client;
using WrapperTest;

namespace WrapperDemo
{
    public partial class Page
    {
        public Page()
        {
            InitializeComponent();
            Decoders.AddDecoder<GifDecoder>();
        }

        private ClientWrapper _wrapper;

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {

            _wrapper = new ClientWrapper("821be233ef7b3a1289f6d4671bedd0e9", HtmlPage.Document.QueryString);
            _wrapper.Log += WrapperLog;
            
            cbx_format.Items.Add(ApiFormat.Json);
            cbx_format.Items.Add(ApiFormat.Xml);
            cbx_format.SelectedIndex = 0;

            initParams.ItemsSource = HtmlPage.Document.QueryString;
            tb_query.Text = HtmlPage.Document.QueryString.Aggregate("", (current, item) => current + (item.Key + "=" + item.Value + "&"));
             
            tb_selfUid.Text = _wrapper.VID;

            cbx_usersHasAppPermission.Items.Add(AppPermissionType.Stream);
            cbx_usersHasAppPermission.Items.Add(AppPermissionType.Notifications);
            cbx_usersHasAppPermission.SelectedIndex = 0;

        }

        void WrapperLog(string obj)
        {
            logList.Items.Add(obj);
        }

        private string GetUid()
        {
            return list_users.SelectedItem == null
                       ? null
                       : ((IUser)list_users.SelectedItem).Uid;
        }

        private string[] GetUids()
        {
            return list_users.SelectedItems.Count == 0 ? null : list_users.SelectedItems.Cast(u => ((IUser)u).Uid).ToArray();
        }

        private string GetAid()
        {
            return list_photoAlbums.SelectedItem == null ? null : ((IPhotoAlbum)list_photoAlbums.SelectedItem).Aid;
        }

        private string[] GetAids()
        {
            if (list_photoAlbums.SelectedItems.Count == 0)
                return null;
            return list_photoAlbums.SelectedItems.Cast(u => ((IPhotoAlbum)u).Aid).ToArray();
        }

        private string[] GetPids()
        {
            if (list_photos.SelectedItems.Count == 0)
                return null;
            return list_photos.SelectedItems.Cast(u => ((IPhoto)u).Pid).ToArray();
        }

        private string[] GetMids()
        {
            if (list_audios.SelectedItems.Count == 0)
                return null;
            return list_audios.SelectedItems.Cast(u => ((IAudio)u).Mid).ToArray();
        }

        private string GetMid()
        {
            return list_audios.SelectedItem == null ? null : ((IAudio)list_audios.SelectedItem).Mid;
        }


        private void InvokeFriendsGet(object sender, RoutedEventArgs e)
        {
            FriendsGet.IsEnabled = false;
            if (cb_friendsGet.IsChecked != null)
                _wrapper.Friends.BeginGet(async => FriendsGet.Dispatcher.BeginInvoke(
                                                       () =>
                                                           {
                                                               try
                                                               {
                                                                   list_users.ItemsSource = _wrapper.Friends.EndGet(async);
                                                               }
                                                               catch (Exception _ex)
                                                               {
                                                                   HtmlPage.Window.Alert(_ex.Message);

                                                               }

                                                               FriendsGet.IsEnabled = true;

                                                           }), cb_friendsGet.IsChecked.Value);
        }

        private void InvokeFriendsGetAppUsers(object sender, RoutedEventArgs e)
        {
            FriendsGetAppUsers.IsEnabled = false;
            if (cb_friendsGetAppUsers.IsChecked != null)
                _wrapper.Friends.BeginGetAppUsers(async => LayoutRoot.Dispatcher.BeginInvoke(
                                                               () =>
                                                                   {
                                                                       try
                                                                       {
                                                                           list_users.ItemsSource =
                                                                               _wrapper.Friends.EndGetAppUsers(async);
                                                                       }
                                                                       catch (Exception _ex)
                                                                       {
                                                                           HtmlPage.Window.Alert(_ex.Message);
                                                                       }
                                                                       FriendsGetAppUsers.IsEnabled = true;
                                                                   }), cb_friendsGetAppUsers.IsChecked.Value);
        }

        private void InvokeUsersGetInfo(object sender, RoutedEventArgs e)
        {
            if (GetUids() == null)
            {
                MessageBox.Show("Select users first");
                return;
            }
            //list_users.ItemsSource = _wrapper.UsersGetInfo(GetUids());
            UsersGetInfo.IsEnabled = false;
            _wrapper.Users.BeginGetInfo(async => LayoutRoot.Dispatcher.BeginInvoke(
                                                     () =>
                                                         {
                                                             try
                                                             {
                                                                 list_users.ItemsSource = _wrapper.Users.EndGetInfo(async);
                                                             }
                                                             catch (Exception _ex)
                                                             {
                                                                 HtmlPage.Window.Alert(_ex.Message);
                                                             }
                                                             UsersGetInfo.IsEnabled = true;
                                                         }), uids: GetUids());


        }

        private void InvokeUsersIsAppUser(object sender, RoutedEventArgs e)
        {
            UsersIsAppUser.IsEnabled = false;
            _wrapper.Users.BeginIsAppUser(async => LayoutRoot.Dispatcher.BeginInvoke(
                                                       () =>
                                                           {
                                                               try
                                                               {
                                                                   HtmlPage.Window.Alert("UsersIsAppUser result: " +
                                                                                         _wrapper.Users.EndIsAppUser(async));
                                                               }
                                                               catch (Exception _ex)
                                                               {
                                                                   HtmlPage.Window.Alert(_ex.Message);
                                                               }
                                                               UsersIsAppUser.IsEnabled = true;
                                                           }), GetUid()
                );

        }

        private void InvokeUsersHasAppPermission(object sender, RoutedEventArgs e)
        {
            UsersHasAppPermission.IsEnabled = false;
            _wrapper.Users.BeginHasAppPermission(
                async => LayoutRoot.Dispatcher.BeginInvoke(
                             () =>
                                 {
                                     try
                                     {
                                         HtmlPage.Window.Alert(
                                             "UsersHasAppPermission result: " +
                                             _wrapper.Users.EndHasAppPermission(async));
                                     }
                                     catch (Exception _ex)
                                     {
                                         HtmlPage.Window.Alert(_ex.Message);
                                     }
                                     UsersHasAppPermission.IsEnabled = true;
                                 }),
                (AppPermissionType)cbx_usersHasAppPermission.SelectedItem, GetUid());


        }

        private void InvokePaymentsOpenDialog(object sender, RoutedEventArgs e)
        {
            PaymentsOpenDialog.IsEnabled = false;
            _wrapper.Payments.BeginOpenDialog(
                async => LayoutRoot.Dispatcher.BeginInvoke(
                             () =>
                                 {
                                     try
                                     {
                                         HtmlPage.Window.Alert(
                                             "PaymentsOpenDialog result: " +
                                             _wrapper.Payments.EndOpenDialog(async));
                                     }
                                     catch (Exception _ex)
                                     {
                                         HtmlPage.Window.Alert(_ex.Message);
                                     }
                                     PaymentsOpenDialog.IsEnabled = true;
                                 }),
                (int)nud_playmentsServiceId.Value,
                tb_playmentsServiceName.Text,
                (int)nud_playmentsOtherPrice.Value,
                (int)nud_playmentsSmsPrice.Value);

        }


        private void InvokeStreamPublish(object sender, RoutedEventArgs e)
        {
            StreamPublish.IsEnabled = false;
            _wrapper.Stream.BeginPublish(
                async => LayoutRoot.Dispatcher.BeginInvoke(
                             () =>
                                 {
                                     try
                                     {
                                         HtmlPage.Window.Alert("StreamPublish result: " +
                                                               _wrapper.Stream.EndPublish(async));
                                     }
                                     catch (Exception _ex)
                                     {
                                         HtmlPage.Window.Alert(_ex.Message);
                                     }
                                     StreamPublish.IsEnabled = true;
                                 }),
                tb_streamText.Text, tb_streamPost.Text, (int)nud_streamImg.Value);

        }

        private void InvokePhotosGetAlbums(object sender, RoutedEventArgs e)
        {
            PhotosGetAlbums.IsEnabled = false;
            _wrapper.Photos.BeginGetAlbums(async => LayoutRoot.Dispatcher.BeginInvoke(
                                                        () =>
                                                            {
                                                                try
                                                                {
                                                                    list_photoAlbums.ItemsSource =
                                                                        _wrapper.Photos.EndGetAlbums(async);
                                                                }
                                                                catch (Exception _ex)
                                                                {
                                                                    HtmlPage.Window.Alert(_ex.Message);
                                                                }
                                                                PhotosGetAlbums.IsEnabled = true;
                                                            }), GetAids());


        }

        private void InvokePhotosGet(object sender, RoutedEventArgs e)
        {

            if (GetAid() == null)
            {
                MessageBox.Show("Select photo album first");
                return;
            }
            PhotosGet.IsEnabled = false;
            _wrapper.Photos.BeginGet(async => LayoutRoot.Dispatcher.BeginInvoke(
                                                  () =>
                                                      {
                                                          try
                                                          {
                                                              list_photos.ItemsSource = _wrapper.Photos.EndGet(async);
                                                          }
                                                          catch (Exception _ex)
                                                          {
                                                              HtmlPage.Window.Alert(_ex.Message);
                                                          }
                                                          PhotosGet.IsEnabled = true;
                                                      }), GetAid() , GetPids());


        }

        private void InvokeAudiosGet(object sender, RoutedEventArgs e)
        {
            AudiosGet.IsEnabled = false;
            _wrapper.Audios.BeginGet(async => LayoutRoot.Dispatcher.BeginInvoke(
                                                  () =>
                                                      {
                                                          try
                                                          {
                                                              list_audios.ItemsSource = _wrapper.Audios.EndGet(async);
                                                          }
                                                          catch (Exception _ex)
                                                          {
                                                              HtmlPage.Window.Alert(_ex.Message);
                                                          }
                                                          AudiosGet.IsEnabled = true;
                                                      }), GetMids());


        }

        private void InvokeAudiosLinkAudio(object sender, RoutedEventArgs e)
        {

            if (GetMid() == null)
            {
                HtmlPage.Window.Alert("Select audio first");
                return;
            }
            AudiosLinkAudio.IsEnabled = false;
            _wrapper.Stream.BeginPublish(
                async => LayoutRoot.Dispatcher.BeginInvoke(
                             () =>
                                 {
                                     try
                                     {
                                         HtmlPage.Window.Alert("AudiosLinkAudio result: " +
                                                               _wrapper.Stream.EndPublish(async));
                                     }
                                     catch (Exception _ex)
                                     {
                                         HtmlPage.Window.Alert(_ex.Message);
                                     }
                                     AudiosLinkAudio.IsEnabled = true;
                                 }),
                GetMid());
        }

        private void list_users_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _list_usersGetInfo.ItemsSource = list_users.SelectedItems;
        }

        private void list_photoAlbums_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _list_photoAlbumsPhotosGetAlbums.ItemsSource = list_photoAlbums.SelectedItems;
        }

        private void list_photos_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _list_photosPhotosGet.ItemsSource = list_photos.SelectedItems;
        }

        private void list_audios_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _list_audiosAudiosGet.ItemsSource = list_audios.SelectedItems;
        }

        private void logList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (logList.SelectedItem != null)
            {
                textBox1.Text = logList.SelectedItem as string;
            }
        }

        private void initParams_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (initParams.SelectedItem != null)
            {
                textBox1.Text = initParams.SelectedItem.ToString();
            }
        }

        private void InvokeGetSelfInfo(object sender, RoutedEventArgs e)
        {
            GetSelfInfo.IsEnabled = false;

            _wrapper.BeginGetSelfInfo(c => LayoutRoot.Dispatcher.BeginInvoke(
                                               () =>
                                                   {
                                                       try
                                                       {
                                                           sp_self.DataContext = _wrapper.EndGetSelfInfo(c);
                                                       }
                                                       catch (Exception _ex)
                                                       {
                                                           HtmlPage.Window.Alert(_ex.Message);
                                                       }
                                                       GetSelfInfo.IsEnabled = true;
                                                   }));
        }

        private void cbx_format_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _wrapper.Format = (ApiFormat)cbx_format.SelectedItem;
        }
    }
}


